<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { Close, Star } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { TravelNoteApi } from '@/api/new/travelNoteApi.js';
import { CommentApi } from '@/api/CommentApi.js';

const props = defineProps({
  articleId: {
    type: [Number, String],
    required: true
  }
});

defineEmits(['close']);

// 文章数据
const article = ref({
  title: '',
  content: '',
  creationTime: '',
  author: {
    name: '',
    avatar: '',
    isFollowed: false
  },
  media: [],
  tags: []
});

// 加载状态
const loading = ref(true);

// 评论相关
const comments = ref([]);
const commentText = ref('');
const commentInputFocused = ref(false);
const expandedComments = ref({});
const replyingTo = ref(null);

// 计算总评论数
const totalComments = computed(() => {
  let count = comments.value.length;
  comments.value.forEach(comment => {
    if (comment.replies) {
      count += comment.replies.length;
    }
  });
  return count;
});

// 获取顶级评论
const topLevelComments = computed(() => {
  return comments.value.filter(comment => !comment.parentCommentID || comment.parentCommentID === 0);
});

// 获取文章详情
const fetchArticleDetails = async (id) => {
  try {
    loading.value = true;
    
    // 获取文章详情
    const articleData = await TravelNoteApi.browseTravelNote(id);
    
    // 获取文章图片
    const imagesData = await TravelNoteApi.getArticleImages(id);
    
    // 处理文章数据
    article.value = {
      ...articleData,
      media: imagesData.map(img => img.imageUrl) || [],
      author: {
        name: getAuthorName(articleData.authorID),
        avatar: getAuthorAvatarUrl(articleData.authorID),
        isFollowed: false // 默认未关注
      },
      tags: articleData.tags ? articleData.tags.split(',') : ['旅行', '摄影', '风景'] // 如果没有标签，使用默认标签
    };
    
    // 获取评论
    await fetchComments(id);
    
  } catch (error) {
    console.error('获取文章详情失败:', error);
    ElMessage.error(`获取文章详情失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

// 获取评论
const fetchComments = async (articleId) => {
  try {
    // 调用真实的评论API
    const commentsData = await CommentApi.getCommentsByArticleId(articleId);
    
    // 处理评论数据，将回复组织成树形结构
    const parentComments = commentsData.filter(c => !c.parentCommentID || c.parentCommentID === 0);
    const childComments = commentsData.filter(c => c.parentCommentID && c.parentCommentID !== 0);
    
    // 为每个父评论添加replies数组
    parentComments.forEach(parent => {
      parent.replies = childComments.filter(child => child.parentCommentID === parent.commentID);
    });
    
    comments.value = parentComments;
    
  } catch (error) {
    console.error('获取评论失败:', error);
    ElMessage.error(`获取评论失败: ${error.message || '未知错误'}`);
    // 使用模拟数据作为备份
    useMockComments();
  }
};

// 使用模拟评论数据（当API调用失败时）
const useMockComments = () => {
  comments.value = [
    {
      commentID: 1,
      userID: 101,
      content: "这个地方真美，我也想去！",
      creationTime: "2023-05-15T10:30:00",
      parentCommentID: 0,
      replies: [
        {
          commentID: 4,
          userID: 102,
          content: "是的，风景太棒了！",
          creationTime: "2023-05-15T11:20:00",
          parentCommentID: 1
        },
        {
          commentID: 5,
          userID: 103,
          content: "请问这是在哪里拍的？",
          creationTime: "2023-05-15T12:15:00",
          parentCommentID: 1
        }
      ]
    },
    {
      commentID: 2,
      userID: 104,
      content: "照片拍得真好，用什么相机拍的？",
      creationTime: "2023-05-16T09:45:00",
      parentCommentID: 0,
      replies: []
    },
    {
      commentID: 3,
      userID: 105,
      content: "分享一下行程安排吧！",
      creationTime: "2023-05-17T14:20:00",
      parentCommentID: 0,
      replies: []
    }
  ];
};

// 提交评论
const submitComment = async () => {
  if (!commentText.value.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }
  
  try {
    const currentTime = new Date().toISOString();
    const parentCommentID = replyingTo.value ? replyingTo.value.commentID : 0;
    
    // 调用真实的评论API
    const commentData = await CommentApi.createComment({
      articleID: props.articleId,
      userID: 100, // 当前用户ID，实际应从用户状态获取
      parentCommentID: parentCommentID,
      content: commentText.value,
      creationTime: currentTime
    });
    
    // 创建新评论对象
    const newComment = {
      commentID: commentData.commentID || Date.now(),
      userID: 100, // 当前用户ID
      content: commentText.value,
      creationTime: currentTime,
      parentCommentID: parentCommentID,
      replies: []
    };
    
    if (replyingTo.value) {
      // 添加回复
      const parentComment = comments.value.find(c => c.commentID === replyingTo.value.parentCommentID || c.commentID === replyingTo.value.commentID);
      if (parentComment) {
        if (!parentComment.replies) {
          parentComment.replies = [];
        }
        parentComment.replies.push(newComment);
      }
      replyingTo.value = null;
    } else {
      // 添加顶级评论
      comments.value.unshift(newComment);
    }
    
    // 清空评论框
    commentText.value = '';
    ElMessage.success('评论发布成功');
    
  } catch (error) {
    console.error('发布评论失败:', error);
    ElMessage.error(`发布评论失败: ${error.message || '未知错误'}`);
  }
};

// 回复评论
const replyToComment = (comment, parentComment = null) => {
  replyingTo.value = {
    commentID: comment.commentID,
    parentCommentID: parentComment ? parentComment.commentID : comment.commentID
  };
  commentText.value = `回复 @${getUserName(comment.userID)}: `;
  // 聚焦评论框
  document.querySelector('.comment-input').focus();
};

// 点赞/取消点赞
const toggleLike = (comment) => {
  // 这里应该调用实际的点赞API
  // 模拟点赞效果
  ElMessage.success('操作成功');
};

// 获取用户头像
const getAvatar = (userID) => {
  const avatars = {
    100: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png', // 当前用户
    101: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    102: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
    103: 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png',
    104: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
    105: 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
  };
  return avatars[userID] || 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png';
};

// 获取作者头像
const getAuthorAvatarUrl = (authorID) => {
  const avatars = {
    1: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    2: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    3: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
  };
  return avatars[authorID] || 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png';
};

// 获取用户名
const getUserName = (userID) => {
  const names = {
    100: '当前用户',
    101: '旅行者A',
    102: '摄影师B',
    103: '探险家C',
    104: '美食家D',
    105: '背包客E'
  };
  return names[userID] || "匿名用户";
};

// 获取作者名
const getAuthorName = (authorID) => {
  const authors = {
    1: '旅行达人',
    2: '风景摄影师',
    3: '美食探索者'
  };
  return authors[authorID] || "Unknown Author";
};

// 获取点赞数
const getLikeCount = (commentID) => {
  const likeCounts = {
    1: 247,
    2: 10,
    3: 5,
    4: 8,
    5: 3
  };
  return likeCounts[commentID] || 0;
};

// 格式化时间
const formatDate = (isoTime) => {
  if (!isoTime) return '';
  
  const date = new Date(isoTime);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(
    date.getDate()
  ).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(
    2,
    '0'
  )}`;
};

// 切换展开/收起状态
const toggleExpandReplies = (commentID) => {
  expandedComments.value[commentID] = !expandedComments.value[commentID];
};

// 关注/取消关注作者
const toggleFollow = async () => {
  try {
    article.value.author.isFollowed = !article.value.author.isFollowed;
    // 这里可以添加实际的API调用
    // await TravelNoteApi.followAuthor(article.value.authorID, token);
    ElMessage.success(article.value.author.isFollowed ? '已关注作者' : '已取消关注');
  } catch (error) {
    console.error('关注操作失败:', error);
    // 恢复状态
    article.value.author.isFollowed = !article.value.author.isFollowed;
    ElMessage.error(`操作失败: ${error.message || '未知错误'}`);
  }
};

// 监听文章ID变化
watch(() => props.articleId, (newId) => {
  if (newId) {
    fetchArticleDetails(newId);
  }
}, { immediate: true });

// 生命周期钩子
onMounted(() => {
  if (props.articleId) {
    fetchArticleDetails(props.articleId);
  }
});
</script>

<template>
  <div class="note-detail-mask">
    <!-- 关闭按钮 -->
    <div class="close-cricle" @click="$emit('close')">
      <div class="close close-mask-white">
        <el-icon><Close /></el-icon>
      </div>
    </div>

    <div class="note-container" v-if="!loading">
      <!-- 媒体轮播 -->
      <div class="media-container">
        <el-carousel height="90vh" v-if="article.media && article.media.length > 0">
          <el-carousel-item v-for="(item, index) in article.media" :key="index">
            <el-image
                style="width: 100%; height: 100%"
                :src="item"
                fit="cover"
            />
          </el-carousel-item>
        </el-carousel>
        <div v-else class="no-media">
          <el-empty description="暂无图片" />
        </div>
      </div>

      <!-- 互动区域 -->
      <div class="interaction-container">
        <div class="author-container">
          <div class="author-me">
            <div class="info">
              <img
                  class="avatar-item"
                  style="width: 40px; height: 40px"
                  :src="article.author.avatar"
              />
              <span class="name">{{ article.author.name }}</span>
            </div>
            <div class="follow-btn">
              <el-button
                  :type="article.author.isFollowed ? 'default' : 'danger'"
                  size="large"
                  round
                  @click="toggleFollow"
              >
                {{ article.author.isFollowed ? '已关注' : '关注' }}
              </el-button>
            </div>
          </div>

          <div class="note-scroller">
            <div class="note-content">
              <div class="title">{{ article.title }}</div>
              <div class="desc">
                <span>{{ article.content }} <br /></span>
                <a
                    v-for="(tag, index) in article.tags"
                    :key="index"
                    class="tag tag-search"
                >
                  {{ tag }}
                </a>
              </div>
              <div class="bottom-container">
                <span class="date">{{ formatDate(article.creationTime) }}</span>
              </div>
            </div>
            <div class="divider interaction-divider"></div>

            <!-- 评论 -->
            <div class="comments-el">
              <div class="comments-container">
                <!-- 总评论数 -->
                <div class="total">共 {{ totalComments }} 条评论</div>

                <!-- 父评论列表 -->
                <div class="list-container">
                  <div v-for="comment in topLevelComments" :key="comment.commentID" class="parent-comment">
                    <!-- 父评论 -->
                    <div class="comment-item">
                      <div class="comment-inner-container">
                        <div class="avatar">
                          <img class="avatar-item" :src="getAvatar(comment.userID)" alt="User Avatar" />
                        </div>
                        <div class="right">
                          <div class="author-wrapper">
                            <div class="author"><a class="name">{{ getUserName(comment.userID) }}</a></div>
                          </div>
                          <div class="content">{{ comment.content }}</div>
                          <div class="info">
                            <div class="date"><span>{{ formatDate(comment.creationTime) }}</span></div>
                            <div class="interactions">
                              <div class="like" @click="toggleLike(comment)">
                                <span class="like-wrapper">
                                  <Star style="width: 1em; height: 1em" />
                                  <span class="count">{{ getLikeCount(comment.commentID) }}</span>
                                </span>
                              </div>
                              <div class="reply" @click="replyToComment(comment)">
                                <span>回复</span>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <!-- 子评论列表 -->
                    <div v-if="comment.replies && comment.replies.length > 0" class="replies-container">
                      <div class="replies-wrapper" :class="{ expanded: expandedComments[comment.commentID] }">
                        <div v-for="reply in comment.replies" :key="reply.commentID" class="reply-item">
                          <div class="comment-inner-container">
                            <div class="avatar">
                              <img class="avatar-item" :src="getAvatar(reply.userID)" alt="User Avatar" />
                            </div>
                            <div class="right">
                              <div class="author-wrapper">
                                <div class="author"><a class="name">{{ getUserName(reply.userID) }}</a></div>
                              </div>
                              <div class="content">{{ reply.content }}</div>
                              <div class="info">
                                <div class="date"><span>{{ formatDate(reply.creationTime) }}</span></div>
                                <div class="interactions">
                                  <div class="like" @click="toggleLike(reply)">
                                    <span class="like-wrapper">
                                      <Star style="width: 1em; height: 1em" />
                                      <span class="count">{{ getLikeCount(reply.commentID) }}</span>
                                    </span>
                                  </div>
                                  <div class="reply" @click="replyToComment(reply, comment)">
                                    <span>回复</span>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 展开/收起按钮 -->
                      <div v-if="comment.replies.length > 2" class="expand-button" @click="toggleExpandReplies(comment.commentID)">
                        {{ expandedComments[comment.commentID] ? '收起' : `展开全部 ${comment.replies.length} 条回复` }}
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 评论输入框 -->
                <div class="comment-comp">
                  <div class="comment-wrapper">
                    <div class="input-wrapper">
                      <textarea
                          class="comment-input"
                          v-model="commentText"
                          placeholder="添加评论..."
                          @focus="commentInputFocused = true"
                          @blur="commentInputFocused = false"
                      ></textarea>
                      <div class="input-buttons">
                        <span>{{ commentText.length }}/1000</span>
                      </div>
                    </div>
                    <div class="submit" @click="submitComment">发布</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
  </div>
</template>

<style scoped lang="less">
.note-detail-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: white;
  z-index: 20;
  overflow: auto;
  display: flex;
  
  .loading-container {
    width: 100%;
    padding: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .close-cricle {
    left: 1.3vw;
    top: 1.3vw;
    position: fixed;
    display: flex;
    z-index: 100;
    cursor: pointer;

    .close-mask-white {
      box-shadow:
        0 2px 8px 0 rgba(0, 0, 0, 0.04),
        0 1px 2px 0 rgba(0, 0, 0, 0.02);
      border: 1px solid rgba(0, 0, 0, 0.08);
    }

    .close {
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 100%;
      width: 40px;
      height: 40px;
      border-radius: 40px;
      cursor: pointer;
      transition: all 0.3s;
    }
  }

  .note-container {
    display: flex;
    width: 100%;
    height: 100%;
    
    .media-container {
      flex: 1;
      height: 100vh;
      
      .no-media {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f5f5;
      }
    }
    
    .interaction-container {
      width: 400px;
      height: 100vh;
      overflow-y: auto;
      padding: 20px;
      border-left: 1px solid #eee;
      
      .author-container {
        .author-me {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
          
          .info {
            display: flex;
            align-items: center;
            
            .avatar-item {
              border-radius: 50%;
              margin-right: 10px;
            }
            
            .name {
              font-weight: bold;
              font-size: 16px;
            }
          }
        }
      }
      
      .note-scroller {
        .note-content {
          margin-bottom: 20px;
          
          .title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 16px;
          }
          
          .desc {
            font-size: 16px;
            line-height: 1.6;
            margin-bottom: 16px;
            
            .tag {
              display: inline-block;
              padding: 4px 8px;
              background-color: #f5f5f5;
              border-radius: 4px;
              margin-right: 8px;
              margin-bottom: 8px;
              font-size: 12px;
              color: #666;
            }
          }
          
          .bottom-container {
            color: #999;
            font-size: 14px;
          }
        }
        
        .divider {
          height: 1px;
          background-color: #eee;
          margin: 20px 0;
        }
        
        .comments-el {
          .comments-container {
            .total {
              font-weight: bold;
              margin-bottom: 20px;
            }
            
            .list-container {
              .parent-comment {
                margin-bottom: 20px;
                
                .comment-item {
                  margin-bottom: 10px;
                }
                
                .replies-container {
                  margin-left: 40px;
                  
                  .replies-wrapper {
                    max-height: 200px;
                    overflow: hidden;
                    
                    &.expanded {
                      max-height: none;
                    }
                    
                    .reply-item {
                      margin-bottom: 10px;
                    }
                  }
                  
                  .expand-button {
                    color: #1890ff;
                    cursor: pointer;
                    margin-top: 10px;
                    font-size: 14px;
                  }
                }
              }
              
              .comment-inner-container {
                display: flex;
                
                .avatar {
                  margin-right: 12px;
                  
                  .avatar-item {
                    width: 32px;
                    height: 32px;
                    border-radius: 50%;
                  }
                }
                
                .right {
                  flex: 1;
                  
                  .author-wrapper {
                    margin-bottom: 4px;
                    
                    .author {
                      font-weight: bold;
                    }
                  }
                  
                  .content {
                    margin-bottom: 8px;
                    line-height: 1.5;
                  }
                  
                  .info {
                    display: flex;
                    justify-content: space-between;
                    color: #999;
                    font-size: 12px;
                    
                    .interactions {
                      display: flex;
                      
                      .like, .reply {
                        margin-left: 16px;
                        cursor: pointer;
                        
                        &:hover {
                          color: #1890ff;
                        }
                      }
                    }
                  }
                }
              }
            }
            
            .comment-comp {
              margin-top: 30px;
              
              .comment-wrapper {
                display: flex;
                align-items: center;
                
                .input-wrapper {
                  flex: 1;
                  position: relative;
                  
                  .comment-input {
                    width: 100%;
                    padding: 10px 40px 10px 15px;
                    border: 1px solid #ddd;
                    border-radius: 20px;
                    resize: none;
                    height: 40px;
                    line-height: 20px;
                    
                    &:focus {
                      outline: none;
                      border-color: #1890ff;
                    }
                  }
                  
                  .input-buttons {
                    position: absolute;
                    right: 15px;
                    top: 50%;
                    transform: translateY(-50%);
                    color: #999;
                    font-size: 12px;
                  }
                }
                
                .submit {
                  margin-left: 10px;
                  background-color: #1890ff;
                  color: white;
                  padding: 0 20px;
                  height: 40px;
                  line-height: 40px;
                  border-radius: 20px;
                  cursor: pointer;
                  
                  &:hover {
                    background-color: #40a9ff;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>